import {Effect,Reducer,Subscription} from 'umi';
import {getUserIdentity,getApiAuthority,getViewAuthority} from '@/services/consumer';
import {IUserIdentity,IApiAuthority,IViewAuthority} from '@/interface/consumer';
import * as consumerApi from '@/services/consumer';

export interface ConsumerModelState{
    userIdentity:IUserIdentity[],
    apiAuthority:IApiAuthority[],
    viewAuthority:IViewAuthority[]
}

export interface ConsumerModelType{
    namespace:'consumer',
    state:ConsumerModelState,
    effects:{
        getUserIdentity:Effect;
        getApiAuthority:Effect;
        getViewAuthority:Effect;
        setIdentity:Effect;
    },
    reducers:{
        save:Reducer<ConsumerModelState>
    }
}

const ConsumerModel:ConsumerModelType = {
    namespace:'consumer',
    state:{
        userIdentity:[],
        apiAuthority:[],
        viewAuthority:[]
    },
    effects:{
        *getUserIdentity({payload},{call,put}){
            const result = yield call(getUserIdentity);
            if(result.code === 1){
                yield put({
                    type:'save',
                    payload:{userIdentity:result.data}
                })
            }
        },
        *getApiAuthority({payload},{call,put}){
            const result = yield call(getApiAuthority);
            if(result.code === 1){
                yield put({
                    type:'save',
                    payload:{apiAuthority:result.data}
                })
            }
        },
        *getViewAuthority({payload},{call,put}){
            const result = yield call(getViewAuthority);
            if(result.code === 1){
                yield put({
                    type:'save',
                    payload:{viewAuthority:result.data}
                })
            }
        },
        *setIdentity({payload},{call,put}){
            const type = payload.type as string;
           
            // const setFun = consumerApi[type];
            // console.log("payload",);
            const result = yield call(consumerApi[type],payload.data);
            return result
        }
    },
    reducers:{
        save(state, action) {
            return {
              ...state,
              ...action.payload,
            };
          }
    }
}

export default ConsumerModel